package com.boe.csb.web.interceptor;

import com.boe.csb.core.entity.UserInfo;
import com.boe.csb.core.service.RoleMapService;
import com.boe.csb.core.service.user.BoeUserService;
import com.boe.csb.web.controller.base.BoeUserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by tianxiang.luo on 16/12/1.
 */
public class UrlInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(UrlInterceptor.class);
    @Autowired
    private RoleMapService roleMapService;
    @Autowired
    private BoeUserService boeUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        /**
         * 先获取 userId
         * 取出用户权限 是否包含  retUrl
         */
        String retUrl = request.getRequestURI();
        String contextPath = request.getContextPath();
        retUrl = retUrl.replaceFirst(contextPath, "");

        UserInfo userInfo = (UserInfo) request.getSession().getAttribute(BoeUserController.USER_KEY);
        if(userInfo!=null){
            String role = boeUserService.findBoeUser(String.valueOf(userInfo.getUserId())).getRole();
            if (!StringUtils.isEmpty(role)) {
                List<String> funcList = roleMapService.getFuncListByRole(role);
                if (!CollectionUtils.isEmpty(funcList)  && funcList.contains(retUrl)) {
                    return true;
                }
            }
        }
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf8");
        response.getWriter().append("{\"resultCode\": 403, \"resultMsg\": \"该用户权限不足\"}");
        return false;
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
